<template>
	<view>
		<view
			style="position: relative;z-index: 8;background: #268cfd url(../../static/images/login.png) right bottom / 294rpx 338rpx no-repeat;">
			<custom background="rgba(0,0,0,0)" :hiddenBtn="true">
				<!-- 扫码注册 华为审核v-if='ios_show'-->
				<view @tap.stop="login_by_invite" class="color-ffffff flex flex-x-y" slot="right"
					style="transform: translateX(-90rpx);">
					<view class="iconfont icon-saoma fs-34"></view>
					<view class="fs-24" style="margin-left: 6rpx;">扫码注册</view>
				</view>
				<!-- 扫码注册 -->
			</custom>
			<view style="height: 380rpx;padding-top: 160rpx;" class="color-ffffff pl-30 login-text-ani">
				<view class="bold" style="font-size: 60rpx;line-height: 34rpx;">
					HELLO,
				</view>
				<view class="fs-30 mt-30">欢迎使用发个信</view>
			</view>
		</view>
		<view class="body"
			style="position: relative;z-index: 10;background-color: #FFFFFF;border-radius: 30rpx;margin-top: -30rpx;">

			<template>
				<view class="form">
					<!-- <view class="title" style="margin-top: 100rpx;">
						{{ type == 1 ?'验证码登录':'密码登录'}}
					</view> -->

					<view class="loginModule color-333333">
						<!-- <view class="loginkey fs-30" style="white-space: nowrap;">手机号</view>
						<view class="separation"></view> -->
						<input name='phone' type="number" maxlength="11" placeholder="输入手机号码" class="input font fs-30"
							placeholder-class="placeholderClass font fs-30" v-model="phoneNum" />
						<!-- <view class="more">获得验证码</view> -->
					</view>
					<view class="loginModule" v-if='type==2'>
						<!-- <view class="loginkey fs-30">密码</view>
						<view class="separation"></view> -->
						<input name='phone' v-model="password" :password="true" placeholder="输入密码" class="input fs-30"
							placeholder-class="font placeholderClass font fs-30" :adjust-position="false" />
						<!-- <view class="more">获得验证码</view> -->
					</view>

					<!-- <view class="loginModule" v-if='type==1'>
						<view class="loginkey" style="width: 150rpx;white-space: nowrap;">图片验证码</view>
						<view class="separation"></view>
						<input class="input" name='code' v-model="imgcode" placeholder="输入图片验证码"
							placeholder-class="placeholderClass" :adjust-position="false" />
						<image @tap="get_code" :src="img" mode="" style="width: 200rpx;height: 80rpx;"></image>
					</view> -->
					<view class="loginModule" v-if='type==1'>
						<!-- <view class="loginkey fs-30">验证码</view>
						<view class="separation"></view> -->
						<input class="input fs-30" name='code' type="number" v-model="verify" placeholder="输入验证码"
							placeholder-class="placeholderClass font fs-30" :adjust-position="false" />
						<view class="more color-333333 fs-30" @click="sendRegistCode">{{time}}</view>
					</view>


					<view class="loginModule color-333333" v-if="invite && type == 1">
						<view class="color-999999 fs-30">邀请码: {{invite}}</view>
					</view>

					<!-- 提示文字 -->
					<view v-if="type == 1" class="fs-24 mt-20" style="color:#888888;margin-left:30rpx;">未注册时登录 , 会自动注册账号
					</view>

					<view style="color: #888888;" class="flex flex-x-b flex-y-center">
						<view class="agreement flex flex-x-y">

							<view class="iconfont icon-weixuanzhong" style="font-size: 26rpx;" v-if="value != 1"
								@tap="choose_value(1)"></view>
							<view class="iconfont icon-xuanzhong color-all" style="font-size: 26rpx;" v-else
								@tap="choose_value(0)"></view>
							<view class="agreementview flex flex-x-y" style="margin-left: 4rpx;">
								<text @tap="choose_value(value == 1 ? 0 : 1)">已阅读</text>
								<text class="color-all"
									@tap="openLocalUrl('https://fgxfile.fagexin.online/fgx/16831966258797947.html','用户服务协议')">《用户服务协议》</text>
								<text>和</text>
								<!-- <text class="color-all"
									@tap="openLocalUrl('https://fgxfile.fagexin.online/fgx/17373535219916478.html','隐私协议')">《隐私协议》</text> -->
								<text class="color-all"
									@tap="openLocalUrl('https://fgxfile.fagexin.online/fgx/17388946264501391.html','隐私协议')">《隐私协议》</text>
							</view>

						</view>
						<view class="flex flex-x-b flex-y-center mt-30 fs-28">
							<view class="flex flex-x-center color-999999">
								<view v-if='type==1' @click="authCode">密码登录</view>
								<view v-if='type==2' @click="cipher">验证码登录</view>
							</view>
						</view>
					</view>

					<button @tap="login_by_phone" class="share-clear login bg-all"
						:class="get_pass()?'':'hui'">登录</button>
				</view>
				<!-- <view class="flex flex-x-b flex-y-center mt-30 fs-28">
					<view class="flex flex-x-center color-all">
						<view v-if='type==1' @click="authCode">密码登录</view>
						<view v-if='type==2' @click="cipher">验证码登录</view>
				
					</view>
					<view class="color-646464" @tap="open_toast" v-if="type==1">收不到验证码？</view>
				</view> -->

			</template>










			<!-- 收不到验证码 -->
			<uni-popup ref="popup" type="center">
				<view style="width: 572rpx;background-color: #FFFFFF;border-radius: 16rpx;">
					<view class="fs-36"
						style="padding-top: 46rpx;text-align: center;font-weight: bold;padding-bottom: 20rpx;">
						收不到验证码
					</view>

					<view class="flex flex-y fs-28 color-666666"
						style="text-align: left;line-height: 60rpx;padding-left: 50rpx;">
						<view>1.请确定手机号是否正确</view>
						<view>2.请确定手机是否停机</view>
						<view>3.可选择使用其他账号登录</view>
					</view>

					<view style="padding-top:18rpx">
						<view style="height: 0.5px;background-color: #EEEEEE;"></view>
						<view @click="close_toast" style="height: 84rpx;" class="flex flex-x-y fs-44 color-all">知道了
						</view>
					</view>
				</view>
			</uni-popup>
			<!-- 收不到验证码 -->
			<powers1 ref="powers1" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></powers1>
			<powers ref="powers"></powers>

		</view>
	</view>
</template>

<script>
	import {
		TUILogin
	} from '@tencentcloud/tui-core';
	import {
		TUIChatKit
	} from '@/TUIKit';
	let info = require('@/siteinfo');
	import powers1 from '@/components/powers/powers1.vue'
	export default {
		components: {
			powers1
		},
		data() {
			return {
				type: 1, // 1验证码登录，2密码登录
				value: 0 + '',
				currentTime: 60,
				time: "获取验证码",
				disabled: "",
				phoneNum: "", //手机号
				password: '', //密码
				verify: '', //验证码
				invite: '',
				img: "", //验证码图片
				uuid: '',
				imgcode: '',
				openid: '', //openid，小程序openid直接登录 手动退出登录会清除缓存的openid

				after: false,
				key: '',
				permissionID: '',

			};
		},
		mounted() {
			let phone = uni.getStorageSync('phone');
			if (phone) {
				this.phoneNum = phone;
			}
		},
		onLoad(e) {
			if (e.invite) {
				this.invite = e.invite;
			}
			// this.get_code();

			if (e.guoqi) {
				// setTimeout(() => {
				// 	this.showToast('身份已过期，请重新登录', 3000);
				// }, 400)
			}

			this.openid = uni.getStorageSync('openid') || '';
			if (this.openid) {
				this.login_by_openid();
			}
			// #ifdef APP-PLUS || H5
			this.after = true;
			// #endif

		},

		methods: {
			get_code() {
				this.request({
					url: '/wechatLogin/code',

				}).then(res => {
					if (res.status == 200 && res.img) {
						this.$nextTick(() => {
							this.img = res.img;
							this.uuid = res.uuid;
							this.imgcode = '';
						})
					}
				});
			},
			authCode() {
				this.type = 2

			},
			cipher() {
				this.type = 1
			},

			//验证手机号码
			inputPhone() {
				console.log(e)
				this.phoneNum = e.detail.value
				if (!(/^1[3456789]\d{9}$/.test(this
						.phoneNum))) {
					if (this.phoneNum.length >= 11) {
						this.showToast('手机号有误');
					}
				}

			},
			//获取验证码
			sendRegistCode() {

				// if (this.imgcode == '') {
				// 	this.showToast('请输入图片验证码');
				// 	return;
				// }

				if (this.time != '获取验证码') {
					this.showToast('请稍等');
					return;
				}

				this.less(() => {


					let that = this;
					console.log(that.phoneNum, "111")
					var reg =
						/^1[3456789]\d{9}$/; //11位手机号码正则
					if (that.phoneNum.length == 0) {
						this.showToast('请输入手机号');
					} else if (reg.test(that.phoneNum) == true) {
						// let currentTime = that.currentTime;
						let interval;
						this.request({
							url: '/login/getCode',
							data: {
								phone: this.phoneNum,
								// uuid: this.uuid,
								// code: this.imgcode
							},
							loading: true,
						}).then(res => {
							if (res.status == 200) {
								this.showToast('验证码已发送', 3000);
								that.time = that.currentTime + 's后重新获取';
								that.disabled = true;
								interval = setInterval(function() {
									that.time = that.currentTime - 1 + 's后重新获取';
									that.currentTime--;
									if (that.currentTime <= 0) {
										clearInterval(interval)
										that.time = '获取验证码',
											that.currentTime = 60,
											that.disabled = false
									}
								}, 1000)
							} else {
								// this.get_code();
							}
						})
					} else {
						this.showToast('请输入正确的手机号');
					}


				})

			},

			//密码登录
			choose_value(val) {
				this.value = val;
			},
			logIn: function(e) {
				console.log(e)
				let that = this;
				if (this.value != 1 + '') {
					this.showToast('请阅读协议');
					return;
				}
				// console.log(e.detail.value.code, 11111111111)
				if (this.phoneNum == "") {
					this.showToast('请输入手机号');
					return;
				}
				if (this.type == 1 && this.verify == "") {
					this.showToast('请输入验证码');
					return;
				}
				if (this.type == 2 && this.password == "") {
					this.showToast('请输入密码');
					return;
				}

				this.to_login();


			},

			close_toast() {
				this.$refs.popup.close();
			},
			open_toast() {
				this.$refs.popup.open();
			},
			get_pass() {
				if (this.value != 1) {
					return false;
				}
				if (!(/^1[3456789]\d{9}$/.test(this
						.phoneNum))) {
					return false;
				}
				if (this.type == 1 && this.verify == "") {
					return false;
				}
				if (this.type == 2 && this.password == "") {
					return false;
				}
				return true;
			},
			to_login() {
				this.less(() => {
					//////////////
					this.request({
						url: this.type == 1 ? '/wechatLogin/msgCode' : '/wechatLogin/pwd',
						method: 'POST',
						loading: true,
						data: {

							msgCode: this.verify,
							password: this.password,
							phone: this.phoneNum,
							parentUserId: this.invite,
						}
					}).then(res => {
						if (res.status == 200) {
							uni.setStorageSync('phone', this.phoneNum);
							uni.setStorageSync('ACCESS_TOKEN', res.data.token);


							let time_now = new Date().getTime();
							res.data.VIP = '';
							if (res.data.user.vipEndTime > time_now) {
								res.data.VIP = 'vip';
								res.data.vip_end_time = this.dateFormat('YY-mm-dd', new Date(res.data.user
									.vipEndTime));
								res.data.hasVip = true;
								res.data.hasVipTime = res.data.vip_end_time;
							}

							if (res.data.user.svipEndTime > time_now) {
								res.data.VIP = 'svip';
								res.data.vip_end_time = this.dateFormat('YY-mm-dd', new Date(res.data.user
									.svipEndTime));
								res.data.hasSvip = true;
								res.data.hasSvipTime = res.data.vip_end_time;
							}
							if (res.data.user.partnerEndTime > time_now) {
								res.data.VIP = 'partner';
								res.data.vip_end_time = this.dateFormat('YY-mm-dd', new Date(res.data.user
									.partnerEndTime));
								res.data.hasPvip = true;
								res.data.hasPartnerTime = res.data.vip_end_time;
								console.log('获取日期', res.data.hasPartnerTime)
							}


							this.vuexSet('user_info', res.data.user, true);


							uni.preloadPage({
								url: '/pages/user/user',

							});

							// uni.preloadPage({
							// 	url: '/pages/game/game',
							// });
							//更新用户信息
							// this.$store.dispatch('refresh_user');

							setTimeout(() => {
								uni.reLaunch({
									url: "/pages/user/user"
								})
							}, 10);
						}
					});
					//////////////
				})
			},
			//openid 登录
			login_by_openid() {

				this.request({
					url: '/wechatLogin/loginByScenario',
					data: {
						scenario: 'login_openId',
						openId: this.openid,
					},
					method: 'POST',
					loading: true,
					toast: false,
				}).then(res => {
					if (res.status == 200 && res.data) {
						//登录成功
						this.vuexSet('user_info', res.data.user, true);
						uni.setStorageSync('ACCESS_TOKEN', res.data.Authorization);
						this.showToast('登录成功');
						this.login_after();
						setTimeout(() => {
							this.uniBack();
						}, 200);
					}
				});
			},
			//获取openid
			get_openid_by_code() {

				// #ifdef MP-WEIXIN
				this.request({
					url: '',
					toast: false,
					login: false,
					data: {},
				}).then(res => {
					if (!res.status || !res.data) return;

				});
				// #endif
			},

			change_after() {
				this.after = true;
			},
			async login_quick(e) {
				// #ifdef MP-WEIXIN
				this.phone_res = e;
				if (this.wx_status === undefined || this.wx_status == 2) {
					this.wx_status = 1;
					return;
				} else if (this.wx_status != 1) {
					return;
				}

				this.click(async () => {
					if (!this.openid) {
						await this.get_weixincode();
					}

					console.log('e', e);

					if (e.detail.code) {
						let phone_res = await this.request({
							url: '/wechatLogin/getPhone',
							data: {
								code: e.detail.code
							}
						});
						console.log('phone_res', phone_res);


						if (!this.rsuccess(phone_res, true)) return;
						this.phoneNum = phone_res.data;


						this.request({
							url: '/wechatLogin/loginByScenario',
							data: {
								scenario: 'login_wx',
								openId: this.openid,
								avatarUrl: this.avatarUrl || '',
								name: this.nickname || '',
								phone: this.phoneNum,
							},
							method: 'POST',
							loading: true,
						}).then(res => {
							if (res.status == 200 && res.data) {
								//登录成功
								this.vuexSet('user_info', res.data.user, true);
								uni.setStorageSync('ACCESS_TOKEN', res.data.Authorization);
								this.showToast('登录成功');
								this.login_after();
								setTimeout(() => {
									this.uniBack();
								}, 200);
							}
						});
					} else {
						this.showToast('请使用手机号登录');
						this.wx_status = undefined;
					}

				});
				this.wx_status == 2;

				// #endif
			},
			async get_weixincode() {
				let aaa = await uni.login();
				console.log('aaa', aaa);
				if (aaa.length == 2 && aaa[1].code) {
					this.weixincode = aaa[1].code;

					let open_data = await this.request({
						url: '/wechatLogin/getOpenId',
						data: {
							code: this.weixincode,
						},
						toast: false,
						login: false,
						loading: true,
					});
					console.log('open_data', open_data);
					if (!this.rsuccess(open_data)) return;
					this.openid = open_data.data.openid;
					this.key = open_data.data.session_key
					uni.setStorage({
						key: 'openid',
						data: open_data.data.openid
					})

				}

			},
			async login_by_phone() {
				if (this.value != 1) {
					this.showToast('请先阅读并勾选用户协议和政策');
					return;
				}
				if (!(/^1[3456789]\d{9}$/.test(this.phoneNum))) {
					this.showToast("请输入正确的手机号");
					return;
				}
				if (this.type == 1) {
					//验证码登录

					if (!this.verify) {
						this.showToast('请输入验证码');
						return;
					}
				}
				if (this.type == 2) {
					if (!this.password) {
						this.showToast('请输入密码');
						return;
					}
				}
				this.click(async () => {
					// #ifdef  MP-WEIXIN
					if (!this.openid) {
						await this.get_weixincode();
					}
					// #endif

					let scenario = '';

					// #ifdef MP-WEIXIN
					scenario = this.type == 1 ? 'login_code' : 'login_password';
					// #endif

					// #ifndef MP-WEIXIN
					scenario = this.type == 1 ? 'login_code' : 'login_password';
					// #endif

					let subData = {
						scenario: scenario,
						// openId: this.openid,
						// avatarUrl: '',
						// name: '',
						phone: this.phoneNum,
						code: this.verify,
						password: this.password,

					};
					if (this.invite) {
						subData.parentUserId = this.invite;
					}
					this.request({
						url: '/login/loginByScenario',
						data: subData,
						method: 'POST',
						loading: true,
					}).then(res => {
						if (res.status == 200 && res.data) {
							//登录成功
							this.vuexSet('user_info', res.data.user, true);
							uni.setStorageSync('ACCESS_TOKEN', res.data.Authorization);
							this.showToast('登录成功');
							console.log('登录成功!!!');
							this.login_after();
							this.login_userSig()
							setTimeout(() => {
								// this.uniBack();
								uni.reLaunch({
									url: "/pages/user/user"
								})
							}, 200);
						}
					});
				});


			},
			login_userSig() {
				let vueVersion = 2;
				// #ifdef VUE3
				vueVersion = 3;
				// #endif
				this.request({
					url: '/user/getTencentUserSig',
				}).then(res => {
					if (!res.status || !res.data) return;
					uni.setStorageSync('userSig', res.data);
					let user_info = uni.getStorageSync('user_info') || {};
					let SDKAppID = info.SDKAPPID; // Your SDKAppID
					let userID = String(user_info.id); // Your userID
					let userSig = res.data; // Your userSig
					TUIChatKit.init();
					console.log('拿到了！！', SDKAppID);
					console.log('拿到了！！', userID);
					console.log('拿到了！！', userSig);

					TUILogin.login({
						SDKAppID: SDKAppID,
						userID: userID,
						userSig: userSig,
						useUploadPlugin: true, // 已购买内容审核服务
						framework: `vue${vueVersion}` //当前开发使用框架
					}).catch(() => {});
				});
			},
			login_after() {
				if (getApp().globalData.CHAT && getApp().globalData.CHAT.CLOSE) {
					getApp().globalData.CHAT.CLOSE();
				}
				getApp().globalData.CHAT.init(1);

				this.$store.dispatch('refresh_friend');
				this.$store.dispatch('refresh_group');
				this.$store.dispatch('refresh_pushid');
			},
			async getUserInfo() {
				let userinfo = await uni.getUserProfile({
					desc: '获取用户昵称和头像',
				});
				console.log('userinfo', userinfo);
				if (userinfo && userinfo[1] && userinfo[1].userInfo) {
					this.avatarUrl = userinfo[1].userInfo.avatarUrl;
					this.nickname = userinfo[1].userInfo.nickName;
				}


				if (this.wx_status === undefined || this.wx_status == 2) {
					this.wx_status = 1;
					return;
				} else if (this.wx_status != 1) {
					return;
				}
				await this.login_quick(this.phone_res);
				this.wx_status == 2
			},
			// 扫码注册
			login_by_invite() {
				if (uni.getSystemInfoSync().platform == "android") {
					this.permissionID = "CAMERA";
					setTimeout(() => {
						this.$refs['powers1'].open();
					}, 500)
				} else {
					this.$refs.powers.open({
						powersType: 'POWERS_CAMERA',
						success: () => {
							////////////
							uni.scanCode({
								success: res => {
									let result = res.result || '';
									this.to_page_by_code(result);
								}
							})
							////////////
						}
					});
				}
			},
			changeAuth() {
				uni.scanCode({
					success: res => {
						let result = res.result || '';
						this.to_page_by_code(result);
					}
				})
				// this.$refs.powers.open({
				// 	powersType: 'POWERS_CAMERA',
				// 	success: () => {
				// 		////////////
				// 		uni.scanCode({
				// 			success: res => {
				// 				let result = res.result || '';
				// 				this.to_page_by_code(result);
				// 			}
				// 		})
				// 		////////////
				// 	}
				// });
			},
		}
	}
</script>

<style lang="scss">
	page {
		// background: #191a1b url(../../static/erqi/logo-bg2.png) left top / 100% 100% no-repeat;
		background-color: #FFFFFF;
		overflow-y: hidden;
		height: 100vh;
	}

	.body {
		padding: 10rpx 30rpx 0 30rpx;
		box-sizing: border-box;
		height: 100vh;
		// background: linear-gradient(180deg, #191a1b, #292a2b);

		.title {
			font-size: 46rpx;
			font-weight: 500;
			color: #333333;
			line-height: 66rpx;
		}

		.subhead {
			margin-top: 20rpx;
			font-size: 28rpx;
			font-weight: 400;
			// text-align: right;
			color: #646464;
			line-height: 28rpx;
			margin-bottom: 40rpx;
		}

		.loginModule {
			display: flex;
			// border-bottom: 2rpx solid #646464;
			align-items: center;
			padding-bottom: 18rpx;
			margin-top: 30rpx;
			background-color: #F5F6F7;
			padding: 24rpx 30rpx;
			border-radius: 16rpx;

			.loginkey {
				height: 42rpx;
				text-align: left;
				color: #646464;
				line-height: 42rpx;
				white-space: nowrap;
			}

			.separation {
				// width: 1px;
				// height: 16rpx;
				// width: 2rpx;
				// background-color: #a9a9a9;
				// margin: 0 18rpx;
			}

			input {
				flex: 1;
				color: #646464;
				font-size: 30rpx;
			}

			.placeholderClass {
				color: #646464;
			}

			.more {
				font-size: 30rpx;
				font-weight: 400;
				text-align: left;
				color: #FD7747;
				line-height: 42rpx;
			}
		}

		.agreement {
			display: flex;
			align-items: center;
			margin-top: 30rpx;


			image {
				width: 26rpx;
				height: 26rpx;
				background: #ffffff;
				margin-right: 8rpx;
			}

			.agreementview {
				font-size: 26rpx;
				font-weight: 400;
				text-align: center;
				color: #888888;
				line-height: 36rpx;

				.color {
					color: #ebd448;
				}
			}

		}

		.login {
			height: 82rpx;
			background: #FFFFFF;
			border-radius: 44rpx;
			text-align: center;
			line-height: 82rpx;
			font-size: 32rpx;
			font-weight: 500;
			text-align: center;
			color: #fff;
			margin-top: 80rpx;
			border-radius: 18rpx;
			width: 524rpx;
			margin-left: auto;
			margin-right: auto;

		}


	}

	.hui {
		opacity: 0.6;
	}

	.login-text-ani {
		animation: login-ani 0.3s linear;
		overflow: hidden;
	}

	@keyframes login-ani {
		0% {
			transform: translateY(200rpx);
			opacity: 0;
		}

		20% {
			opacity: 0;
		}

		100% {
			transform: translateY(0);
			opacity: 1;
		}
	}
</style>